<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/11 0011
 * Time: 8:52
 * 邀请业务处理
 */
namespace Api\Controller;
use Think\Controller;
class PollingController extends Controller {

    /**
     * 轮询指派订单
     */
    function pollingappointorder(){
        $us=  I("un");
        $ps=  I("ps");

        $this->assign('un', $us);
        $this->assign('ps', $ps);
        $this->display();
    }

    /**
     * 订单重发和强制指派
     */
    function  order_appoint(){
        $this->verification_username();

        if(empty($_POST['time']))exit();
        set_time_limit(0);//无限请求超时时间
        $i=0;
        while (true){
            //sleep(1);
            usleep(5000000);//挂起5秒
            $i++;
//            dump('指派开始时间：'.date('Y-m-d H:i:s',time()));
            $appoint_ret = order_appoint();//强制指派，消息不发聊天室。
            //若得到数据则马上返回数据给客服端，并结束本次请求
//            dump('指派结束时间：'.date('Y-m-d H:i:s',time()));
//            dump('重发查询开始时间：'.date('Y-m-d H:i:s',time()));
            $ret = order_repeat();//重发3次，到聊天室，即所有跑客都可以再次接到
//            dump('重发查询结束时间：'.date('Y-m-d H:i:s',time()));
//            dump($ret);
//            $ret = 1;
//            $test_arr = json_decode('[{"uid":"9","token":"4780bb2ea68100bad290bae9446a5c13","city_id":128,"res_type":"美食|早餐|","order_type":2,"total_mileage":"0.50","remark":"","remark_voice":"","send_address":"测试发送地址1","send_address_floor":"","send_mobile":"13949036223","send_longit":113.61094359086691,"send_latit":34.80449689104783,"reci_address":"测试接受地址1","reci_address_floor":"","reci_mobile":0,"reci_longit":113.60786240296768,"reci_latit":34.80184409802425,"conveyance_id":1,"up_server":"","goods_amount":0,"fee":0,"coupon_id":"11","company_id":1,"is_reservation":0,"reservation_time":"","voucher_no":"WKTRADENO2016921182059160224","order_amount":"9.60","is_have_price":0,"pay_method":1,"real_amount":"1.60"},'.
//                '{"uid":"9","token":"4780bb2ea68100bad290bae9446a5c13","city_id":128,"res_type":"早餐|","order_type":1,"total_mileage":"0.50","remark":"","remark_voice":"","send_address":"测试发送地址","send_address_floor":"","send_mobile":"13949036223","send_longit":113.61094359086691,"send_latit":34.80449689104783,"reci_address":"测试接受地址","reci_address_floor":"","reci_mobile":0,"reci_longit":113.60786240296768,"reci_latit":34.80184409802425,"conveyance_id":1,"up_server":"","goods_amount":0,"fee":0,"coupon_id":"11","company_id":1,"is_reservation":0,"reservation_time":"","voucher_no":"WKTRADENO2016921182059160224","order_amount":"9.60","is_have_price":0,"pay_method":1,"real_amount":"1.60"}]',true);

            if($ret){
                $arr=array('success'=>"1",'name'=>'帮你跑腿重发','text'=>$ret);
//                $arr=array('success'=>"1",'name'=>'帮你跑腿','text'=>$ret);
            }else
                $arr=array('success'=>"0",'name'=>'帮你跑腿重发','text'=>'');
//            dump(json_encode($test_arr));
            echo json_encode($arr);
//            echo '{"success":"1","name":"帮你跑腿","text":[{"is_reservation":0,"res_type":"\u9910\u5385","voucher_no":"WKTRADENO201692593240762437","city_id":128,"send_address_floor":"","reci_address_floor":"0","real_amount":"4.00","coupon_id":"2","queue_address":"\u6cb3\u5357\u7701\u56fd\u5bb6\u5927\u5b66\u79d1\u6280\u56ed\u4e1c\u533a\u521b\u65b0\u56ed1\u53f7-A\u5ea7","order_amount":"12.00","send_latit":34.8038,"replace_mobile":"13137154660","reci_address":"0","queue_time":"2016-10-25 9:32:27","hour_long":"30","company_id":1,"uid":"2","token":"e683b31ea6c7a532574b20b53e7b34e9","reci_longit":34.80251,"pay_method":1,"send_longit":113.6086,"reci_latit":113.6072,"reci_mobile":"0","remark":"","order_type":3,"user_id":2,"order_id":1,"conveyance_id":0,"is_have_price":0}]}';
            exit();

            //服务器($_POST['time']*0.5)秒后告诉客服端无数据
            if($i==$_POST['time']){
                $arr=array('success'=>"0",'name'=>'无可需要强制指派的订单','text'=>$rand);
                echo json_encode($arr);
                exit();
            }

        }

    }

    /**
     * 预约单 提前短信提醒
     *
     */
    function  order_reservation(){
        $this->verification_username();

        if(empty($_POST['time']))
            exit();
        set_time_limit(0);//无限请求超时时间
        $i=0;
        while (true){
            //sleep(1);
            usleep(5000000);//挂起5秒
            $i++;
            //若得到数据则马上返回数据给客服端，并结束本次请求

            $ret = order_reservation_msm();

            if($ret){
//                    $arr=array('success'=>"1",'name'=>'xiaocai','text'=>'{"uid":"9","token":"4780bb2ea68100bad290bae9446a5c13","city_id":128,"res_type":"美食|早餐|","order_type":2,"total_mileage":"0.50","remark":"","remark_voice":"","send_address":"河南电力工业学校","send_address_floor":"","send_mobile":"13949036223","send_longit":113.61094359086691,"send_latit":34.80449689104783,"reci_address":"大学科技园18号楼","reci_address_floor":"","reci_mobile":0,"reci_longit":113.60786240296768,"reci_latit":34.80184409802425,"conveyance_id":1,"up_server":"","goods_amount":0,"fee":0,"coupon_id":"11","company_id":1,"is_reservation":0,"reservation_time":"","voucher_no":"WKTRADENO2016921182059160224","order_amount":"9.60","is_have_price":0,"pay_method":1,"real_amount":"1.60"}');
                $arr=array('success'=>"1",'name'=>'帮你跑腿预约单提醒','text'=>$ret);

            }else
                $arr=array('success'=>"0",'name'=>'帮你跑腿预约单提醒','text'=>'');

            echo json_encode($arr);
            exit();


            //服务器($_POST['time']*0.5)秒后告诉客服端无数据
            if($i==$_POST['time']){
                $arr=array('success'=>"0",'name'=>'无需要提前短信提醒的预约单','text'=>'');
                echo json_encode($arr);
                exit();
            }

        }

    }
    /**
     * 极光推送
     *
     */
    function  jpush_polling(){

        if(empty($_POST['time']))
            exit();
        set_time_limit(0);//无限请求超时时间
        $i=0;
        while (true){
            //sleep(1);
            usleep(5000000);//挂起5秒
            $i++;
            //若得到数据则马上返回数据给客服端，并结束本次请求

            $ret = $this->jpush_dispatch();

            if($ret==1){
                $arr=array('success'=>"1",'name'=>'帮你跑客极光推送','text'=>"极光推送成功");

            }elseif($ret == 2 )
                $arr=array('success'=>"1",'name'=>'帮你跑客极光推送','text'=>"无需推送");
            else
                $arr=array('success'=>"0",'name'=>'帮你跑客极光推送','text'=>'极光推送失败');

            echo json_encode($arr);
            exit();


            //服务器($_POST['time']*0.5)秒后告诉客服端无数据
            if($i==$_POST['time']){
                $arr=array('success'=>"0",'name'=>'极光推送超时','text'=>'');
                echo json_encode($arr);
                exit();
            }

        }

    }
    /**
     * 轮询订单、跑客活动表，
     * 有新订单、跑客处于后台状态，则推送消息
     */
    function jpush_dispatch(){

        //查询已支付的、待分配的、下单时间在3天内的订单，进行推送
        $order_resmsm_db = M('order_resmsm');
        $order_resmsm_obj = $order_resmsm_db->field('order_id,order_type,order_lat,order_lng,company_id,jpush_count,jpush_dispatch_ids')->where('pay_status=1 and status = 1 and UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(order_time) < 24*60*60*3')->select();
//        dump($order_resmsm_db->getLastSql());
//        dump($order_resmsm_obj);

        if($order_resmsm_obj) {
            //循环要推送的所有订单
            foreach ($order_resmsm_obj as $key => $value) {
                $order_obj = M('order')->field('order_id')->where('order_id = '.$value['order_id'].' and status != 1')->find();//再次反查，如果此时订单的状态不是待分配状态，则不推送
//                dump(M('order')->getLastSql());
//                dump($order_obj);

                //订单表中，状态修改了，也不再推送此订单
                if($order_obj)
                    continue;
                // start 查出3公里内、处于后台的、没被推送的跑客
                $lon = doubleval($value['order_lng']);
                $lat = doubleval($value['order_lat']);
                $squares = returnSquarePoint($lon, $lat, 3);//得出以订单经纬度为中心，3公里的左上角的经纬度，和右下角的经纬度
                $where = " ";

                if ($value['company_id'] && $value['company_id'] != 1) {//团队条件
                    $where = " and d.company_id=" . $value['company_id'];
                }

                if ($value['jpush_dispatch_ids']) {//已推送的跑客id
                    $where .= " and dispatch_id not in (" . $value['jpush_dispatch_ids'] . ") ";
                    $old = json_decode($value['jpush_dispatch_ids'],true);
                }

                //处于后台的，24小时内的，没有推送过的，团队条件的，3公里直线范围内的跑客，进行推送
                $Model = M();
                $sql = "select GROUP_CONCAT(jpush_id) as jpush_ids,GROUP_CONCAT(dispatch_id) as dispatch_ids".
                    ",GROUP_CONCAT(ROUND(6378.138*2*ASIN(SQRT(POW(SIN((latitude*PI()/180-" . $lat . "*PI()/180)/2),2)+COS(latitude*PI()/180)*COS(" . $lat . "*PI()/180)*POW(SIN((longitude*PI()/180-" . $lon . "*PI()/180)/2),2)))*1000)) as distance".
                    " from db_dispatch_active d where  latitude>{$squares['right-bottom']['lat']} and latitude < {$squares['left-top']['lat']} and longitude > {$squares['left-top']['lng']} and longitude < {$squares['right-bottom']['lng']} " .
                    " and is_background = 1 and UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(place_up_time) < 24*60*60" .
                    $where .
                    "ORDER BY distance";

                $jpush_arr = $Model->query($sql);
//                dump($Model->getLastSql());
//                dump($jpush_arr);

                //end 查出3公里内、处于后台的、没被推送的跑客
                if ($jpush_arr&&$jpush_arr[0]['jpush_ids']) {
                    $jpush_ids = $jpush_arr[0]['jpush_ids'];
                    $jpush_id_arr=explode(',',$jpush_ids);//需要推送的jpush_id数组
                    $new_ids = $jpush_arr[0]['dispatch_ids'];

                    $extras['order_id']=$value['order_id'];//额外参数
                    $extras['order_type']=$value['order_type'];
                    $extras['distance']=$jpush_arr[0]['distance'];
//                    dump($jpush_arr);
//                    dump($jpush_arr[0]['jpush_ids']);

                    import("Vendor.Jpush.pnJpush");
                    $jpush = new \pnJpush();
                    $jpush_ret = $jpush->push(array('registration_id' => $jpush_id_arr), '', '您有一个新订单', $extras);//推送操作
//                    dump($jpush_ret);
                    $jpush_ret_arr = json_decode($jpush_ret,true);
                    if(isset($jpush_ret_arr['msg_id']) && !empty($jpush_ret_arr['msg_id'])){//推送成功
                        if($old){
                            $new_ids=$old.','.$new_ids;//组合已推送的id串，和本次推送的id串
                        }
                        $order_resmsm_db->where(array('order_id' => $value['order_id']))
                            ->setField(array('jpush_count' => $value['jpush_count'] + 1, 'jpush_dispatch_ids' => $new_ids));//退送次数加1，记录已推送的跑客id串
                    } else {
                        return 0;
                    }
                }
//                dump('end');
            }
            return 1;
        }else {
            return 2;
        }
    }
    /**
     * 验证用户token
     */
    function verification_username()
    {
        $username = I("get.un");
        $password = I("get.ps");

        if (!$username || !$password) {
        $this->error("验证失败");
        }

        $ret = sp_compare_password($password,'###f077a72ce63bfa54a8aa016e1e557110');
        if($username == 'ccxx' && $ret){
            return true;
        }else
            $this->error("验证失败");

    }

    function  testatlon(){
        $order_db = M('order');
        $order_obj = $order_db->where(array('order_id'=>26))->find();
        getPn_nearby_oneinfo($order_obj['reci_latit'],$order_obj['reci_longit'],1);
    }
    /**
     * 轮询订单、跑客活动表，
     * 有新订单、跑客处于后台状态，则推送消息
     */
    function test_jpush(){

        //查询已支付的、待分配的、下单时间在3天内的订单，进行推送
        $order_resmsm_db = M('order_resmsm');
        $order_resmsm_obj = $order_resmsm_db->field('order_id,order_type,order_lat,order_lng,company_id,jpush_count,jpush_dispatch_ids')->where('pay_status=1 and status = 1 and UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(order_time) < 24*60*60*3')->select();
//        dump($order_resmsm_db->getLastSql());
//        dump($order_resmsm_obj);

        if($order_resmsm_obj) {
            //循环要推送的所有订单
            foreach ($order_resmsm_obj as $key => $value) {
                $order_obj = M('order')->field('order_id')->where('order_id = '.$value['order_id'].' and status != 1')->find();//再次反查，如果此时订单的状态不是待分配状态，则不推送
//                dump(M('order')->getLastSql());
//                dump($order_obj);

                //订单表中，状态修改了，也不再推送此订单
                if($order_obj)
                    continue;
                // start 查出3公里内、处于后台的、没被推送的跑客
                $lon = doubleval($value['order_lng']);
                $lat = doubleval($value['order_lat']);
                $squares = returnSquarePoint($lon, $lat, 3);//得出以订单经纬度为中心，3公里的左上角的经纬度，和右下角的经纬度
                $where = " ";

                if ($value['company_id'] && $value['company_id'] != 1) {//团队条件
                    $where = " and d.company_id=" . $value['company_id'];
                }

                if ($value['jpush_dispatch_ids']) {//已推送的跑客id
                    $where .= " and dispatch_id not in (" . $value['jpush_dispatch_ids'] . ") ";
                    $old = json_decode($value['jpush_dispatch_ids'],true);
                }

                //处于后台的，24小时内的，没有推送过的，团队条件的，3公里直线范围内的跑客，进行推送
                $Model = M();
                $sql = "select GROUP_CONCAT(jpush_id) as jpush_ids,GROUP_CONCAT(dispatch_id) as dispatch_ids".
                    ",GROUP_CONCAT(ROUND(6378.138*2*ASIN(SQRT(POW(SIN((latitude*PI()/180-" . $lat . "*PI()/180)/2),2)+COS(latitude*PI()/180)*COS(" . $lat . "*PI()/180)*POW(SIN((longitude*PI()/180-" . $lon . "*PI()/180)/2),2)))*1000)) as distance".
                    " from db_dispatch_active d where  latitude>{$squares['right-bottom']['lat']} and latitude < {$squares['left-top']['lat']} and longitude > {$squares['left-top']['lng']} and longitude < {$squares['right-bottom']['lng']} " .
                    " and is_background = 1 and UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(place_up_time) < 24*60*60" .
                    $where .
                    "ORDER BY distance";

                $jpush_arr = $Model->query($sql);
//                dump($Model->getLastSql());
//                dump($jpush_arr);

                //end 查出3公里内、处于后台的、没被推送的跑客
                if ($jpush_arr&&$jpush_arr[0]['jpush_ids']) {
                    $jpush_ids = $jpush_arr[0]['jpush_ids'];
                    $jpush_id_arr=explode(',',$jpush_ids);//需要推送的jpush_id数组
                    $new_ids = $jpush_arr[0]['dispatch_ids'];

                    $extras['order_id']=$value['order_id'];//额外参数
                    $extras['order_type']=$value['order_type'];
                    $extras['distance']=$jpush_arr[0]['distance'];
//                    dump($jpush_arr);
//                    dump($jpush_arr[0]['jpush_ids']);

                    import("Vendor.Jpush.pnJpush");
                    $jpush = new \pnJpush();
                    $jpush_ret = $jpush->push(array('registration_id' => $jpush_id_arr), '', '您有一个新订单', $extras);//推送操作
                    dump($jpush_ret);
                    $jpush_ret_arr = json_decode($jpush_ret,true);
                    if(isset($jpush_ret_arr['msg_id']) && !empty($jpush_ret_arr['msg_id'])){//推送成功
                        if($old){
                            $new_ids=$old.','.$new_ids;//组合已推送的id串，和本次推送的id串
                        }
                        $order_resmsm_db->where(array('order_id' => $value['order_id']))
                            ->setField(array('jpush_count' => $value['jpush_count'] + 1, 'jpush_dispatch_ids' => $new_ids));//退送次数加1，记录已推送的跑客id串
                    } else {
                        return 0;
                    }
                }
                dump('end');
            }
            return 1;
        }else {
            return 2;
        }
    }
    function  testorder_appoint(){
        order_appoint();
    }
}